package com.elm.controller;

import com.elm.common.ApiResponse;
import com.elm.mapper.PersonMapper;
import com.elm.mapper.UserAuthorityMapper;
import com.elm.po.LoginRequest;
import com.elm.po.Person;
import com.elm.po.User;
import com.elm.service.UserService;
import com.elm.util.JwtUtil;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api")
public class UserController {

    @Autowired
    private UserService userService;
    
	@Autowired
	private UserAuthorityMapper userAuthorityMapper;

    // 登录（公开）
    @PostMapping("/auth")
    public Map<String, String> getUserByNameByPass(@RequestBody LoginRequest loginRequest) {
    		String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();
            User user = userService.getUserByNameByPass(username, password);
            if (user == null) {
                throw new RuntimeException("用户名或密码错误");
            }
            String token = JwtUtil.generateToken(user.getUsername(), userAuthorityMapper.getAuthorityById(user.getId()));
            Map<String, String> result = new HashMap<>();
            result.put("id_token", token);
            return result;
    } 
    
    @PostMapping("/users")
    public ApiResponse<User> createUser(@RequestBody User user) {
    	try {
    		User createdUser = userService.createUser(user);
    		if(createdUser==null)
    		{
    			return ApiResponse.error("500","新增用户失败");
    		}
            return ApiResponse.success(createdUser);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    
    @GetMapping("/user")
    public ApiResponse<User> getUserByName() {
    	try {
            return ApiResponse.success(userService.getUserByName());
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    
    @GetMapping("/username/{username}")
    public ApiResponse<User> getUserByName(@PathVariable String username) {
    	try {
    		User foundUser = userService.getUserByName(username);
//    		if(foundUser == null) {
//    			return ApiResponse.error("404", "找不到该用户");
//    		}
            return ApiResponse.success(foundUser);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }

    @PostMapping("/password")
    public ApiResponse<Integer> updatePassword(@RequestBody User user) {
    	try {
    		int result = userService.updatePassword(user);
    		if(result==0) {
    			return ApiResponse.error("500", "修改密码失败");
    		}
            return ApiResponse.success(result);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }

    @PostMapping("/banUser/{targetUserId}")
    public ApiResponse<User> banUser(@PathVariable int targetUserId) {
    	try {
    		User user = userService.banUser(targetUserId);
    		if(user==null || user.getStatus()!="banned") {
    			return ApiResponse.error("500", "封禁用户失败");
    		}
            return ApiResponse.success(user);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }

    @PostMapping("/staff/{staffUserId}/{businessId}")
    public ApiResponse<User> addStaff(@PathVariable int staffUserId,@PathVariable int businessId) {
    	try {
    		User user = userService.addStaff(staffUserId,businessId);
    		if(user==null) {
    			return ApiResponse.error("500", "新增员工失败");
    		}
            return ApiResponse.success(user);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    
    @DeleteMapping("/staff/{staffUserId}/{businessId}")
    public ApiResponse<Integer> deleteStaff(@PathVariable int staffUserId,@PathVariable int businessId) {
    	try {
    		int result = userService.deleteStaff(staffUserId,businessId);
    		if(result==0) {
    			return ApiResponse.error("500", "删除员工失败");
    		}
            return ApiResponse.success(result);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    
    @GetMapping("/staff/{businessId}")
    public ApiResponse<List<Person>> getAllStaff(@PathVariable int businessId) {
    	try {
            return ApiResponse.success(userService.getAllStaff(businessId));
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    
    @GetMapping("/register")
    public ApiResponse<User> register(@RequestBody User user) {
    	try {
    		User user1 = userService.createUser(user);
    		if(user1==null) {
    			return ApiResponse.error("500", "新增用户失败");
    		}
            return ApiResponse.success(user1);
       } catch (RuntimeException e) {
           return ApiResponse.error("400", e.getMessage());
       } catch (Exception e) {
           return ApiResponse.error("500", "系统错误：" + e.getMessage());
       } 
    }
    @GetMapping("/getAuthority")
    public String getAuthority() {
    	return userService.getAuthority();
    }
}